import React, { useState, useEffect, useRef } from "react";
import {
  StyleSheet,
  View,
  TextInput,
  FlatList,
  TouchableOpacity,
  Image,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from "react-native";
import { useLocalSearchParams, useRouter } from "expo-router";
import { MaterialCommunityIcons } from "@expo/vector-icons";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";
import { IceBreaker } from "@/components/chat/IceBreaker";
import { AIReplyAssistant } from "@/components/chat/AIReplyAssistant";
import { chatAPI } from "@/services/chatAPI";
import { useAuth } from "@/contexts/AuthContext";

// 模拟用户数据 - 后续会从API获取
const USERS = {
  "1": {
    name: "张阿姨",
    avatar: { uri: "https://randomuser.me/api/portraits/women/65.jpg" },
  },
  "2": {
    name: "李大爷",
    avatar: { uri: "https://randomuser.me/api/portraits/men/72.jpg" },
  },
  "3": {
    name: "王奶奶",
    avatar: { uri: "https://randomuser.me/api/portraits/women/70.jpg" },
  },
  "4": {
    name: "赵叔叔",
    avatar: { uri: "https://randomuser.me/api/portraits/men/67.jpg" },
  },
  "5": {
    name: "刘大妈",
    avatar: { uri: "https://randomuser.me/api/portraits/women/68.jpg" },
  },
};

export default function ChatDetailScreen() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const colorScheme = useColorScheme();
  const tintColor = Colors[colorScheme ?? "light"].tint;
  const flatListRef = useRef(null);
  const { userToken } = useAuth();

  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState([]);
  const [lastMessage, setLastMessage] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [user, setUser] = useState(USERS[id as string]);

  // 加载聊天历史
  useEffect(() => {
    if (userToken && id) {
      loadChatHistory();
    } else {
      setIsLoading(false);
    }
  }, [userToken, id]);

  // 格式化消息时间
  const formatMessageTime = (date) => {
    const now = new Date();
    const messageDate = new Date(date);

    // 如果是今天的消息，只显示时间
    if (messageDate.toDateString() === now.toDateString()) {
      return messageDate.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });
    }

    // 如果是昨天的消息
    const yesterday = new Date(now);
    yesterday.setDate(now.getDate() - 1);
    if (messageDate.toDateString() === yesterday.toDateString()) {
      return `昨天 ${messageDate.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      })}`;
    }

    // 其他情况显示日期和时间
    return `${
      messageDate.getMonth() + 1
    }月${messageDate.getDate()}日 ${messageDate.toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    })}`;
  };

  // 加载聊天历史
  const loadChatHistory = async () => {
    try {
      setIsLoading(true);
      const response = await chatAPI.getConversation(id as string);

      if (response.data && response.data.length > 0) {
        const formattedMessages = response.data.map((msg) => ({
          id: String(msg.id),
          text: msg.content,
          sender: msg.senderId ? "me" : "other",
          time: formatMessageTime(new Date(msg.createdAt)),
        }));
        setMessages(formattedMessages);

        // 如果有消息，设置最后一条消息
        if (formattedMessages.length > 0) {
          setLastMessage(formattedMessages[formattedMessages.length - 1]);
        }
      }
    } catch (error) {
      console.error("获取聊天历史失败:", error);
      // 如果API调用失败，使用模拟数据（仅用于开发测试）
    } finally {
      setIsLoading(false);
    }
  };

  // 自动滚动到底部
  useEffect(() => {
    if (flatListRef.current && messages.length > 0) {
      setTimeout(() => {
        flatListRef.current.scrollToEnd({ animated: true });
      }, 100);
    }
  }, [messages]);

  // 监听消息变化，更新最后一条消息
  useEffect(() => {
    if (messages.length > 0) {
      setLastMessage(messages[messages.length - 1]);
    }
  }, [messages]);

  const handleSend = async () => {
    if (message.trim() === "") return;

    const newMessage = {
      id: String(Date.now()),
      text: message,
      sender: "me",
      time: formatMessageTime(new Date()),
    };

    setMessages([...messages, newMessage]);
    const sentMessage = message;
    setMessage("");

    try {
      // 发送消息到后端
      await chatAPI.sendMessage(parseInt(id as string, 10), sentMessage);

      // 在实际应用中，这里应该通过WebSocket接收对方的回复
      // 这里我们模拟一个延迟，然后重新加载消息列表
      setTimeout(() => {
        loadChatHistory();
      }, 1000);
    } catch (error) {
      console.error("发送消息失败:", error);
    }
  };

  // 处理从IceBreaker组件选择的消息
  const handleIceBreakerMessage = (selectedMessage: string) => {
    setMessage(selectedMessage);
  };

  // 处理从AIReplyAssistant组件选择的回复
  const handleSelectReply = (reply: string) => {
    setMessage(reply);
  };

  const renderMessage = ({ item }) => {
    const isMe = item.sender === "me";

    return (
      <View
        style={[
          styles.messageContainer,
          isMe ? styles.myMessage : styles.otherMessage,
        ]}
      >
        {!isMe && <Image source={user.avatar} style={styles.avatar} />}
        <View style={styles.messageWrapper}>
          <View
            style={[
              styles.messageBubble,
              isMe ? styles.myBubble : styles.otherBubble,
            ]}
          >
            <ThemedText style={[styles.messageText, isMe && { color: "#fff" }]}>
              {item.text}
            </ThemedText>
          </View>
          <ThemedText
            style={[
              styles.timeText,
              isMe ? styles.myTimeText : styles.otherTimeText,
            ]}
          >
            {item.time}
          </ThemedText>
        </View>
      </View>
    );
  };

  // 渲染加载指示器
  const renderLoading = () => {
    if (!isLoading) return null;

    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size='large' color={tintColor} />
        <ThemedText style={styles.loadingText}>加载聊天记录...</ThemedText>
      </View>
    );
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
        >
          <MaterialCommunityIcons
            name='arrow-left'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
        <ThemedText style={styles.headerTitle}>{user?.name}</ThemedText>
        <TouchableOpacity style={styles.moreButton}>
          <MaterialCommunityIcons
            name='dots-vertical'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
      </View>

      {isLoading ? (
        renderLoading()
      ) : (
        <FlatList
          ref={flatListRef}
          data={messages}
          renderItem={renderMessage}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.messagesList}
          inverted={false}
        />
      )}

      {/* AI推荐回复组件 */}
      <AIReplyAssistant
        onSelectReply={handleSelectReply}
        lastMessage={lastMessage}
      />

      {/* AI辅助聊天破冰组件 */}
      <IceBreaker onSelectMessage={handleIceBreakerMessage} />

      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        keyboardVerticalOffset={100}
        style={styles.inputContainer}
      >
        <TextInput
          style={styles.input}
          value={message}
          onChangeText={setMessage}
          placeholder='输入消息...'
          placeholderTextColor='#999'
          multiline
        />
        <TouchableOpacity
          onPress={handleSend}
          style={[
            styles.sendButton,
            !message.trim() && styles.sendButtonDisabled,
          ]}
          disabled={!message.trim()}
        >
          <MaterialCommunityIcons
            name='send'
            size={24}
            color={message.trim() ? "#fff" : "#ccc"}
          />
        </TouchableOpacity>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  backButton: {
    padding: 5,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: "bold",
  },
  moreButton: {
    padding: 5,
  },
  messagesList: {
    padding: 15,
    paddingBottom: 30,
  },
  messageContainer: {
    flexDirection: "row",
    marginBottom: 15,
    maxWidth: "80%",
  },
  myMessage: {
    alignSelf: "flex-end",
    marginLeft: "auto",
  },
  otherMessage: {
    alignSelf: "flex-start",
    marginRight: "auto",
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
  },
  messageWrapper: {
    flexDirection: "column",
  },
  messageBubble: {
    padding: 12,
    borderRadius: 18,
    maxWidth: "100%",
  },
  myBubble: {
    backgroundColor: "#0a7ea4",
    borderBottomRightRadius: 5,
  },
  otherBubble: {
    backgroundColor: "#F0F0F0",
    borderBottomLeftRadius: 5,
  },
  messageText: {
    fontSize: 16,
    lineHeight: 22,
  },
  timeText: {
    fontSize: 12,
    marginTop: 5,
    color: "#999",
  },
  myTimeText: {
    alignSelf: "flex-end",
  },
  otherTimeText: {
    alignSelf: "flex-start",
  },
  inputContainer: {
    flexDirection: "row",
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: "#E1E1E1",
    backgroundColor: "#fff",
  },
  input: {
    flex: 1,
    backgroundColor: "#F0F0F0",
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 10,
    maxHeight: 100,
    fontSize: 16,
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "#0a7ea4",
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 10,
  },
  sendButtonDisabled: {
    backgroundColor: "#E1E1E1",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});
